<?php


namespace App\Models;


use Spatie\QueryBuilder\AllowedFilter;

class QueryBuilder extends \Spatie\QueryBuilder\QueryBuilder
{
    public function filters($filters = [], bool $replace = false): self
    {
        if (!$replace && is_array($filters)) {
            $filters = array_merge(
                [
                    AllowedFilter::exact('id'),

                    // 需要在模型中 use App\Models\Traits\TimeScope;  已经在BaseModel中引入 继承 BaseModel的模型均可使用
                    AllowedFilter::scope('CreatedAtOfDay'),
                    AllowedFilter::scope('CreatedAtBefore'),
                    AllowedFilter::scope('CreatedAtAfter'),
                    AllowedFilter::scope('CreatedAtBetween'),
                    AllowedFilter::scope('UpdatedAtBefore'),
                    AllowedFilter::scope('UpdatedAtAfter'),
                    AllowedFilter::scope('UpdatedAtBetween'),

                ],
                $filters
            );
        }
        return parent::allowedFilters($filters);
    }

    public function fields($fields = [], bool $replace = false): self
    {
        if (!$replace && is_array($fields)) {
            $fields = array_merge(['id'], $fields);
        }
        return parent::allowedFields($fields);
    }


    public function includes($includes = [], bool $replace = false): self
    {
        if (!$replace && is_array($includes)) {
            // 无默认关联
            $includes = array_merge([], $includes);
        }
        return parent::allowedIncludes($includes);
    }

    public function sorts($sorts = [], bool $replace = false): self
    {
        if (!$replace && is_array($sorts)) {
            // 默认支持id排序
            $sorts = array_merge(['id'], $sorts);
        }
        return parent::allowedSorts($sorts);
    }

    public function page()
    {
        if (request()->header('all')) {
            // 请求时头部携带all请求头表示获取所有记录
            return self::get();
        }
        return self::Paginate();
    }
}
